package com.wn.netty.group;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @FileName: MySimpleChannelHandler
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2020/8/5 - 11:38
 * @Version: V1.0
 * @Company: 东方微银科技（北京）有限公司
 */
public class SimpleServerChannelHandler extends SimpleChannelInboundHandler<String> {

    private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        CHANNEL_GROUP.writeAndFlush(LocalDateTime.now().toString() + "客户端[" + channel.remoteAddress() + "]" + "进入群聊\r\n");
        CHANNEL_GROUP.add(channel);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(LocalDateTime.now().toString() + "客户端[" + channel.remoteAddress() + "]" + "上线了");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("------------------------------channelRead0");
        Channel channel = ctx.channel();
        System.out.println(LocalDateTime.now().toString() + "[" + channel.remoteAddress() + "]说: " + msg);
        CHANNEL_GROUP.forEach(ch -> {
            if (Objects.equals(ch, channel)) {
                return;
            }
            ch.writeAndFlush(LocalDateTime.now().toString() + "[" + channel.remoteAddress() + "]说: " + msg + "\r\n");
        });
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(LocalDateTime.now().toString() + "客户端[" + channel.remoteAddress() + "]" + "下线了");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        CHANNEL_GROUP.writeAndFlush(LocalDateTime.now().toString() + "客户端[" + channel.remoteAddress() + "]" + "离开群聊\r\n");
        System.out.println("channel_group size: " + CHANNEL_GROUP.size());
    }

}
